package com.sp2p.system.interceptor;

import java.util.Date;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
import com.shove.Convert;
import com.sp2p.entity.User;
import com.sp2p.service.UserService;
import com.sp2p.util.DateUtil;

public class WechatAutoLoginInterceptor implements Interceptor {
	private static final long serialVersionUID = 1L;
	public static Log log = LogFactory.getLog(WechatAutoLoginInterceptor.class);

	private ServletContext context;
	private UserService userService;
	private boolean isInit = false; // 防止重复初始化参数

	public void destroy() {
	}

	public void init() {
	}

	public String intercept(ActionInvocation invocation) throws Exception {
		// 初始化参数，防止重复获取
		if (!isInit) {
			context = ServletActionContext.getServletContext();
			WebApplicationContext ctx = WebApplicationContextUtils
					.getWebApplicationContext(context);
			userService = ctx.getBean(UserService.class);
			isInit = true; // 只初始化一次
		}

		HttpSession session = ServletActionContext.getRequest().getSession();
		String unionid = session.getAttribute("unionid") == null ? "" : session
				.getAttribute("unionid").toString();
		if ("".equals(unionid)) {
			return invocation.invoke();
		}
		User user = (User)session.getAttribute("user");
		Map<String, String> autoInfo = userService.queryWchatAutoLoginInfo(unionid);
		if ( null != autoInfo && autoInfo.size() > 0 && null == user) {
			int isAuto = Convert.strToInt(autoInfo.get("isAuto"), 0);
			long uid = Convert.strToLong(autoInfo.get("userId"), -1);
			if (isAuto == 1 && uid > 0) {
				user = userService.wchatAutoLoginSession(uid);
				session.setAttribute("user", user);
			}

		}

		return invocation.invoke();
	}
}
